package net.xin.action;


import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

import net.xin.model.User;
import net.xin.servlet.UserServlet;

public class UserAction {
	
	private User user;
	UserServlet servlet;	/*由applicationContext.xml初始化,提高灵活性【控制反转】*/
	
	public User getUser() {
		return user;
	}


	public void setUser(User user) {
		this.user = user;
	}

	public UserServlet getServlet() {
		return servlet;
	}

	@Resource(name="servlet")	/*调用，注入*/
	public void setServlet(UserServlet servlet) {
		this.servlet = servlet;
	}


	public String add() {
		servlet.add(user);
		ActionContext.getContext().getSession().put("USER", user);
		return "main";
	}
	
	public String checkExists() throws IOException {
		boolean flag=servlet.checkExists(user);
		HttpServletResponse res=ServletActionContext.getResponse();
		PrintWriter out=res.getWriter();
		if(flag) {
			out.print("1");
		}else {
			out.print("0");
		}
		return null;
	}
	
	public String login() {
		boolean flag=servlet.checkExists(user);
		HttpServletRequest req=ServletActionContext.getRequest();
		HttpSession session=req.getSession();
		String result="login";
		session.setAttribute("USER", user);
		if(flag) {
			result="main";
		}
		return result;
	}
	
	public String logout() {
		HttpServletRequest req=ServletActionContext.getRequest();
		HttpSession session=req.getSession();
		//使session失效
		session.setAttribute("USER", null);
		return "main";
	}
}
